package com.hitrust.gs.util;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


public class AESCoder extends ISymmetricAlgorithmCoder {
	
	/**
	 * ��Կ�㷨
	 */
	public static final String KEY_ALGORITHM = "AES";
	
	/**
	 * ���ܽ����㷨/����ģʽ/��䷽ʽ
	 */
	public static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
	
	private static Key toKey(byte[] key) throws Exception {
		SecretKey secretKey = new SecretKeySpec(key, KEY_ALGORITHM);
		return secretKey;
	}

	public byte[] decrypt(byte[] data, byte[] key) throws Exception {
		Key k = toKey(key);
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, k);
		return cipher.doFinal(data);
	}

	public byte[] encrypt(byte[] data, byte[] key) throws Exception {
		Key k = toKey(key);
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, k);
		return cipher.doFinal(data);
	}

	public byte[] initKey() throws Exception {
		KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
		kg.init(128);
		SecretKey secretKey = kg.generateKey();
		return secretKey.getEncoded();
	}

	public static void main(String[] args) throws Exception {
		String inputStr = "AESdsfasdgfsdagdsa";
		System.out.println("输入:\t" + inputStr);
		
		AESCoder desCoder = new AESCoder();
		String key = desCoder.initKeyToBase64Str();
		System.out.println("KEY:\t" + key);
		
		String encryptData = desCoder.encrypt(inputStr, key);
		System.out.println("密文:\t" + encryptData);
		
		String decryptData = desCoder.decrypt(encryptData, key);
		System.err.println("解密:\t" + decryptData);
	}
}
